use anyhow::{Error, Result};
use serde::{Deserialize, Serialize};


use super::DataBase;


#[derive(sqlx::FromRow,Debug,Serialize,Deserialize)]
pub struct Users{
    userid: String,
    username:String,
    password:String,
    is_login: i64,
    create_time: String,
    update_time: String,
    delete_time: String,
    is_deleted: i64,
}

impl Users {
    pub async fn new(userid:&str,username:&str,password:&str) -> Result<Self>{
        Ok(Users { 
            userid: userid.to_string(), 
            username: username.to_string(), 
            password: password.to_string(), 
            is_login: 0, 
            create_time: chrono::Local::now().format("%Y%m%d%H%M%S").to_string(), 
            update_time: chrono::Local::now().format("%Y%m%d%H%M%S").to_string(), 
            delete_time: String::new(), 
            is_deleted: 0 
        })
    }
}

pub async fn insert_user(user: Users) -> Result<()> {
    let pool = DataBase::new().await?.db_pool;
    let is_exists:(i64,) = sqlx::query_as("select count(1) from users where userid=?").bind(user.userid.clone()).fetch_one(&pool).await?;
    println!("{}",is_exists.0);
    if is_exists.0.eq(&0){
        sqlx::query("insert into users select ?,?,?,?,?,?,?,?")
        .bind(user.userid)
        .bind(user.username)
        .bind(user.password)
        .bind(user.is_login)
        .bind(user.create_time)
        .bind(user.update_time)
        .bind(user.delete_time)
        .bind(user.is_deleted)
        .execute(&pool).await?;
        Ok(())
    }else {
        Err(Error::msg("用户已注册"))
    }
}

pub async fn set_is_login(userid: &str,is_login: i64) -> Result<()> {
    let pool = DataBase::new().await?.db_pool;
    sqlx::query("update users set is_login=? where userid=?").bind(is_login)
        .bind(userid)
        .execute(&pool).await?;

    Ok(())
}

pub async fn get_loin_users() -> Result<Vec<Users>> {
    let pool = DataBase::new().await?.db_pool;

    let users = sqlx::query_as::<_,Users>("select * from users where is_login=1").fetch_all(&pool).await?;
    Ok(users)
}

#[tokio::test]
async fn test_insert_user() -> Result<()> {
    let user = Users::new("adafasfa","admin","admin").await?;
    insert_user(user).await?;
    let now_time = chrono::Local::now().format("%Y%m%d%H%M%S").to_string();
    println!("{:#?}",now_time);

    Ok(())
}